package org.ruanjj.multithread.JUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class SharaData {
    private int number = 0;
    private ReentrantLock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    //模仿生产者
    public void increaseNumber(){
       try{
          lock.lock();
          while(number != 0){
              condition.await();
          }
          number++;
          condition.signalAll();
       } catch (InterruptedException e) {
           throw new RuntimeException(e);
       } finally {
           lock.unlock();
       }
    }

    //模仿消费者
    public void decreaseNumber(){
        try{
            lock.lock();
            while(number == 0){
                condition.await();
            }
            number--;
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}

class shareTest{
    public static void main(String[] args) {
        SharaData sharaData = new SharaData();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName()+i+"生产");
                sharaData.increaseNumber();
            }
        },"t1").start();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+i+"过来消费了");
                sharaData.decreaseNumber();
                System.out.println(Thread.currentThread().getName()+i+"消费完成");
            }
        },"t2").start();
    }
}
